var app = getApp();
const song = require('../../utils/song.js')
const Lyric = require('../../utils/lyric.js')
const util = require('../../utils/util.js')

const SEQUENCE_MODE = 1
const RANDOM_MOD = 2
const SINGLE_CYCLE_MOD = 3

Page({
  data: {
    playurl: '',
    playIcon: 'icon-play',
    cdCls: 'pause',
    currentLyric: null,
    currentLineNum: 0,
    toLineNum: -1,
    currentSong: null,
    dotsArray: new Array(2),
    currentDot: 0,
    playMod: SEQUENCE_MODE,
    uid: '',
    songList:[],
    defaultImage:"https://y.gtimg.cn/music/photo_new/T002R300x300M000001VqGlj2Oj52k.jpg?max_age=2592000"
  },

  onShow: function () {

    console.log("onShow begin")

    //判断一下多种情况
    /***
     * 判断一下多种情况
     * 1：当前没有播放音乐，需要播放音乐，songlist已更新
     * 2：当前在播放音乐，页面切进来，音乐应该继续
     * 3：当前正在播放音乐，需要切换其他音乐
     */

    const backgroundAudioManager = wx.getBackgroundAudioManager()
    if(backgroundAudioManager.paused){
      this._init()
    }
    else{
      if(app.globalData.newSong==1){
        this._init()
      }
      else{
        this.update_process();

      }
    }

    
    this.setData({
      uid: this.getUid()
    })
  },

  //初始化
  _init: function () {

    console.log("_init start")

    console.log(app.globalData);

    let songList = (app.globalData.songList.length && app.globalData.songList) || wx.getStorageSync('songList')
    let currentSong = app.globalData.songList[app.globalData.currentIndex] || (songList && songList[app.globalData.currentIndex])
    let duration = currentSong && currentSong.duration


    this.setData({
      currentSong: currentSong,
      duration: this._formatTime(duration),
      songList: songList,
      currentIndex: app.globalData.currentIndex
    })



    this._createAudio(currentSong.songUrl)
  },


  // 获取背景播放音乐的songmidid
  _getBackPlayfileName: function () {
    return new Promise((resolve, reject) => {
      wx.getBackgroundAudioPlayerState({
        success: function (res) {
          var dataUrl = res.dataUrl
          let ret = dataUrl && dataUrl.split('?')[0].split('/')[3]
          resolve({ret, res})
        },
        fail: function (e) {
          let ret = false
          reject(ret)
        }
      })
    })
  },

 

  getUid () {
    let _uid = JSON.parse(JSON.stringify(this.data.uid))
    if (_uid) {
      return _uid
    }
    if (!_uid) {
      const t = (new Date()).getUTCMilliseconds()
      _uid = '' + Math.round(2147483647 * Math.random()) * t % 1e10
    }
    return _uid
  },

  update_process(){
    const backgroundAudioManager = wx.getBackgroundAudioManager()

        // 监听背景音频播放进度更新事件，只有小程序在前台时会回调。
        backgroundAudioManager.onTimeUpdate(()=>{
          const currentTime = backgroundAudioManager.currentTime
    
          console.log("onTimeUpdate")
          console.log(currentTime)
    
          this.setData({
            currentTime: this._formatTime(currentTime),
            percent: currentTime / this.data.currentSong.duration,
            duration:this._formatTime(this.data.currentSong.duration) 
          })
    
        });



  },

  // 创建播放器
  _createAudio: function (playUrl) {


    console.log("_createAudio begin")
    console.log(playUrl)

    // wx.playBackgroundAudio({
    //   dataUrl: playUrl,
    //   title: this.data.currentSong.name,
    //   coverImgUrl: this.data.currentSong.image
    // })

    const backgroundAudioManager = wx.getBackgroundAudioManager()
    backgroundAudioManager.title = this.data.currentSong.songName;
    backgroundAudioManager.epname = this.data.currentSong.author;
    backgroundAudioManager.singer = this.data.currentSong.author;
    backgroundAudioManager.coverImgUrl = 'http://y.gtimg.cn/music/photo_new/T002R300x300M000003rsKF44GyaSk.jpg?max_age=2592000'
    backgroundAudioManager.src = playUrl;

    
    

    //新歌播放完毕，恢复状态
    app.globalData.newSong=0;

    // 监听音乐播放。
    backgroundAudioManager.onPlay(()=>{
      this.setData({
        playIcon: 'icon-pause',
        cdCls: 'play'
      })
    })

    // 监听音乐暂停。
    backgroundAudioManager.onPause(()=>{
      this.setData({
        playIcon: 'icon-play',
        cdCls: 'pause'
      })
    })

    // 监听音乐停止。
    backgroundAudioManager.onStop(()=>{

      if (this.data.playMod === SINGLE_CYCLE_MOD) {
        this._init()
        return
      }
      this.next()
    })

    this.update_process()


    
  },
  _formatTime: function (interval) {
    interval = interval | 0
    const minute = interval / 60 | 0
    const second = this._pad(interval % 60)
    return `${minute}:${second}`
  },
  /*秒前边加0*/
  _pad(num, n = 2) {
    let len = num.toString().length
    while (len < n) {
      num = '0' + num
      len++
    }
    return num
  },
  changeMod: function () {
    let playMod = this.data.playMod + 1
    if (playMod > SINGLE_CYCLE_MOD) {
      playMod = SEQUENCE_MODE
    }
    this.setData({
      playMod: playMod
    })
  },
  prev: function () {
    app.globalData.currentIndex = this.getNextIndex(false)
    this._init()
  },
  next: function () {
    app.globalData.currentIndex = this.getNextIndex(true)
    this._init()
  },
  goOneMin:function (){
    const backgroundAudioManager = wx.getBackgroundAudioManager()
    let gapTime = backgroundAudioManager.duration-backgroundAudioManager.currentTime;
    if(gapTime>60){
      backgroundAudioManager.seek(backgroundAudioManager.currentTime+60)
      this.update_process();
    }
    else{
      wx.showToast({
        title: "剩余时间不足60秒",
        icon: 'none'
      })
    }

  },
  backOneMin:function(){
    const backgroundAudioManager = wx.getBackgroundAudioManager()

    if(backgroundAudioManager.currentTime>60){
      backgroundAudioManager.seek(backgroundAudioManager.currentTime-60)
      this.update_process();
    }
    else{
      wx.showToast({
        title: "开始时间不足60秒",
        icon: 'none'
      })
    }
  },

  /**
   * 获取不同播放模式下的下一曲索引
   * @param nextFlag: next or prev
   * @returns currentIndex
   */
  getNextIndex: function (nextFlag) {
    let ret,
        currentIndex = app.globalData.currentIndex,
        mod = this.data.playMod,
        len = this.data.songList.length
    if (mod === RANDOM_MOD) {
      ret = util.randomNum(len)
    } else {
      if (nextFlag) {
        ret = currentIndex + 1 == len ? 0 : currentIndex + 1
      } else {
        ret = currentIndex - 1 < 0 ? len - 1 : currentIndex - 1
      }
    }
    return ret
  },
  togglePlaying: function () {

    const backgroundAudioManager = wx.getBackgroundAudioManager()
    if(backgroundAudioManager.paused) {
      backgroundAudioManager.play();
    }
    else{
      backgroundAudioManager.pause();
    }

    // wx.getBackgroundAudioPlayerState({
    //   success: function (res) {
    //     var status = res.status
    //     if (status == 1) {
    //       wx.pauseBackgroundAudio()
    //     } else {
    //       wx.playBackgroundAudio()
    //     }
    //   }
    // })
  },
  openList: function () {
    if (!this.data.songList.length) {
      return
    }
    this.setData({
      translateCls: 'uptranslate'
    })
  },
  close: function () {
    this.setData({
      translateCls: 'downtranslate'
    })
  },
  playthis: function (e) {
    const index = e.currentTarget.dataset.index
    app.globalData.currentIndex = index
    this._init()
    this.close()
  },
  changeDot: function (e) {
    this.setData({
      currentDot: e.detail.current
    })
  }
})
